package cn.com.dhc.chesishan;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloForm2 extends HttpServlet {
	private static final long serialVersionUID = 680663124579478491L;

	// 使用表单的 POST 方法实例

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		/*
		 * 创建cookie要在读取有数值的页面才可以读到值
		 */
		
		// 为名字和姓氏创建 Cookies
		Cookie firstName = new Cookie("first_name",
				request.getParameter("first_name"));
		Cookie lastName = new Cookie("last_name",
				request.getParameter("last_name"));

		// 为两个 Cookies 设置过期日期为 24 小时后
		firstName.setMaxAge(60 * 60 * 24);
		lastName.setMaxAge(60 * 60 * 24);

		// 在响应头中添加两个 Cookies
		response.addCookie(firstName);
		response.addCookie(lastName);

		String title = "使用表单的 POST 方法";
		String docType = "<!doctype html public \"-//w3c//dtd html 4.0"
				+ "transitional//en\">\n";
		out.println(docType + "<html>\n" + "<head><title>" + title
				+ "</head></title>\n" + "<body bgcolor=\"#f0f0f0\">\n"
				+ "<h1 align=\"center\">\n" + title + "</h1>\n" + "<ul>\n"
				+ "<li><b>名字</b>:\n" + request.getParameter("first_name")
				+ "\n" + "<li><b>姓氏</b>:\n" + request.getParameter("last_name")
				+ "\n" + "</ul>\n" + "</body></html>");
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
